package net.roybi.SysInfo;

import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.security.cert.X509Certificate;
import java.util.ArrayList;

import net.roybi.SysInfo.ui.ViewPagerCustom;
import net.roybi.SysInfo.utils.SignatureGettter;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.pm.Signature;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.util.ArrayMap;
import android.support.v4.view.ViewPager;
import android.text.ClipboardManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;
import net.roybi.SysInfo.R;

public class ActivityApp extends FragmentActivity {
    TabHost mHost;
    ViewPagerCustom mViewPager;
    TabsAdapter mTabsAdapter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.app);

        ResolveInfo info = getIntent().getParcelableExtra("info");
        setTitle(info.loadLabel(getPackageManager()));

        mHost = (TabHost) findViewById(android.R.id.tabhost);
        mHost.setup();

        mViewPager = (ViewPagerCustom) findViewById(R.id.pager);

        mTabsAdapter = new TabsAdapter(this, mHost, mViewPager);

        Bundle bd = new Bundle();
        // bd.putParcelable("info", info);
        // mTabsAdapter.addTab(mHost.newTabSpec("1").setIndicator("ResolveInfo"),
        // ListFragment.class, bd);
        // bd = new Bundle();
        // bd.putParcelable("info", info.activityInfo);
        // mTabsAdapter.addTab(mHost.newTabSpec("2").setIndicator("ActivityInfo"),
        // ListFragment.class, bd);
        // bd = new Bundle();
        bd.putParcelable("info", info.activityInfo.applicationInfo);
        mTabsAdapter.addTab(mHost.newTabSpec("3").setIndicator(getString(R.string.fg_appinfo)),
                ListFragment.class, bd);
        bd = new Bundle();
        PackageManager pm = getPackageManager();
        int flags = PackageManager.GET_RECEIVERS | PackageManager.GET_SERVICES
                | PackageManager.GET_PROVIDERS | PackageManager.GET_INSTRUMENTATION
                | PackageManager.GET_INTENT_FILTERS | PackageManager.GET_RESOLVED_FILTER
                | PackageManager.GET_META_DATA | PackageManager.GET_SHARED_LIBRARY_FILES
                | PackageManager.GET_ACTIVITIES | PackageManager.GET_SIGNATURES
                | PackageManager.GET_GIDS | PackageManager.GET_PERMISSIONS;
        PackageInfo packageInfo = null;
        try {
            packageInfo = pm.getPackageInfo(info.activityInfo.packageName, flags);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
            return;
        }
        bd.putParcelable("info", packageInfo);
        mTabsAdapter.addTab(mHost.newTabSpec("4").setIndicator(getString(R.string.fg_pkginfo)),
                ListFragment.class, bd);
        if (savedInstanceState != null) {
            mHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
        }

        Button but = (Button) findViewById(R.id.but1);
        final String packageName = info.activityInfo.packageName;
        but.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                if (Build.VERSION.SDK_INT >= 9) { // above 2.3
                    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", packageName, null);
                    intent.setData(uri);
                } else { // below 2.3
                    final String appPkgName = (Build.VERSION.SDK_INT == 8 ? "pkg"
                            : "com.android.settings.ApplicationPkgName");
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setClassName("com.android.settings",
                            "com.android.settings.InstalledAppDetails");
                    intent.putExtra(appPkgName, packageName);
                }
                startActivity(intent);
            }
        });
        but = (Button) findViewById(R.id.but2);
        final Signature sig = packageInfo.signatures[0];
        but.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                X509Certificate cert = SignatureGettter.parseSignature(sig);
                if (cert == null) {
                    Toast.makeText(ActivityApp.this, getString(R.string.error_signature),
                            Toast.LENGTH_LONG).show();
                    return;
                }
                StringBuilder str = new StringBuilder();
                str.append(getString(R.string.cert_sigalgname) + cert.getSigAlgName() + "\n");
                str.append(getString(R.string.cert_publickey) + cert.getPublicKey().toString()
                        + "\n");
                str.append(getString(R.string.cert_serialnumber)
                        + cert.getSerialNumber().toString() + "\n");
                str.append(getString(R.string.cert_subjectdn) + cert.getSubjectDN().toString()
                        + "\n");
                str.append(getString(R.string.cert_printfinger)
                        + SignatureGettter.getFingerprint(sig.toByteArray()) + "\n");
                // same as above
                // try {
                // str.append(getString(R.string.cert_printfinger) +
                // SignatureGettter.getFingerprint(cert.getEncoded()) + "\n");
                // } catch (CertificateEncodingException e) {
                // e.printStackTrace();
                // }
                new AlertDialog.Builder(ActivityApp.this)
                        .setTitle(getString(R.string.app_name))
                        .setMessage(str.toString())
                        .setNegativeButton(getString(android.R.string.cancel),
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //nothing
                                        dialog.cancel();
                                    }
                                })
                        .setPositiveButton(getString(android.R.string.copy),
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        TextView tv = (TextView) ((AlertDialog)dialog).findViewById(android.R.id.message);
                                        if (tv == null)
                                            return;
                                        ClipboardManager cm = (ClipboardManager) getSystemService(Activity.CLIPBOARD_SERVICE); 
                                        cm.setText(tv.getText());
                                        Toast.makeText(ActivityApp.this, "add clipboard text:"+tv.getText(), Toast.LENGTH_SHORT).show();
                                    }
                                })
                         .setCancelable(true).create().show();
            }
        });
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("tab", mHost.getCurrentTabTag());
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    public static class TabsAdapter extends FragmentPagerAdapter implements
            TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener {
        private final Context mContext;
        private final TabHost mTabHost;
        private final ViewPager mViewPager;
        private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();

        static final class TabInfo {
            @SuppressWarnings("unused")
            private final String tag;
            private final Class<?> clss;
            private final Bundle args;

            TabInfo(String _tag, Class<?> _class, Bundle _args) {
                tag = _tag;
                clss = _class;
                args = _args;
            }
        }

        static class DummyTabFactory implements TabHost.TabContentFactory {
            private final Context mContext;

            public DummyTabFactory(Context context) {
                mContext = context;
            }

            @Override
            public View createTabContent(String tag) {
                View v = new View(mContext);
                v.setMinimumWidth(0);
                v.setMinimumHeight(0);
                return v;
            }
        }

        public TabsAdapter(FragmentActivity activity, TabHost tabHost, ViewPager pager) {
            super(activity.getSupportFragmentManager());
            mContext = activity;
            mTabHost = tabHost;
            mViewPager = pager;
            mTabHost.setOnTabChangedListener(this);
            mViewPager.setAdapter(this);
            mViewPager.setOnPageChangeListener(this);
        }

        public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args) {
            tabSpec.setContent(new DummyTabFactory(mContext));
            String tag = tabSpec.getTag();

            TabInfo info = new TabInfo(tag, clss, args);
            mTabs.add(info);
            mTabHost.addTab(tabSpec);
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return mTabs.size();
        }

        @Override
        public Fragment getItem(int position) {
            TabInfo info = mTabs.get(position);
            return Fragment.instantiate(mContext, info.clss.getName(), info.args);
        }

        @Override
        public void onTabChanged(String tabId) {
            int position = mTabHost.getCurrentTab();
            mViewPager.setCurrentItem(position);
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            TabWidget widget = mTabHost.getTabWidget();
            int oldFocusability = widget.getDescendantFocusability();
            widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
            mTabHost.setCurrentTab(position);
            widget.setDescendantFocusability(oldFocusability);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    }

    public static class ListFragment extends Fragment {

        public ListFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.list, container, false);
            return v;
        }

        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);

            Parcelable info = getArguments().getParcelable("info");

            ArrayMap<String, Object> map = GetClassFileds(info);
            // List<String> array = new ArrayList<String>();
            // for (Entry<String, Object> entry: map.entrySet()) {
            // String value;
            // if (entry.getValue()!=null) {
            // value = entry.getValue().toString();
            // }
            // else {
            // value = "null";
            // }
            // array.add(entry.getKey()+":"+value);
            // }

            ListView list = (ListView) getView().findViewById(R.id.list);
            InfoAdapter adapter = new InfoAdapter(map, getActivity());
            list.setAdapter(adapter);
            // list.setAdapter(new ArrayAdapter<String>(getActivity(),
            // android.R.layout.simple_list_item_1, array));
        }
    }

    static class InfoAdapter extends BaseAdapter {
        ArrayMap<String, Object> mMap;
        Context mContext;

        public InfoAdapter(ArrayMap<String, Object> map, Context context) {
            mMap = map;
            mContext = context;
        }

        @Override
        public int getCount() {
            return mMap.size();
        }

        @Override
        public Object getItem(int position) {
            return mMap.keyAt(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // ViewHolder holder;

            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(
                        android.R.layout.simple_list_item_1, parent, false);
            } else {
            }

            String text;
            final Object value = mMap.valueAt(position);
            if (value != null) {
                text = mMap.keyAt(position) + ":" + value.toString();
                convertView.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        if (value.getClass().isArray()) {
                            StringBuilder sb = new StringBuilder();
                            for (int i = 0; i < Array.getLength(value); i++) {
                                sb.append(Array.get(value, i).toString() + "\n");
                            }
                            AlertDialog dlg = new AlertDialog.Builder(mContext).setMessage(
                                    sb.toString()).create();
                            dlg.setCanceledOnTouchOutside(true);
                            dlg.show();
                        }
                        // if (value instanceof int[]) {
                        // StringBuilder sb = new StringBuilder();
                        // for (Object obj: (int[])value) {
                        // sb.append(obj.toString()+"\n");
                        // }
                        // AlertDialog dlg = new
                        // AlertDialog.Builder(mContext).setMessage(sb.toString()).create();
                        // dlg.setCanceledOnTouchOutside(true);
                        // dlg.show();
                        // }
                    }
                });
            } else {
                text = mMap.keyAt(position) + ":null";
                convertView.setOnClickListener(null);
            }

            ((TextView) convertView).setText(text);
            return convertView;
        }

    }

    public static ArrayMap<String, Object> GetClassFileds(Object obj) {
        Field[] fs = obj.getClass().getFields();
        ArrayMap<String, Object> map = new ArrayMap<String, Object>();
        for (Field f : fs) {
            if (f.getModifiers() == (Modifier.PUBLIC)) {
                try {
                    map.put(f.getName(), f.get(obj));
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return map;
    }
}